package com.duoec.dw.lineage.service.analyser.partition;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLAssignItem;
import com.duoec.dw.lineage.exceptions.LineageAnalyseException;
import com.duoec.dw.lineage.dto.TableLineageDto;
import com.duoec.dw.lineage.service.analyser.HivePartitionAnalyser;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xuwenzhen
 */
@Service
public class AssignItemAnalyser implements HivePartitionAnalyser {
    /**
     * 获取当前类处理的类型
     *
     * @return SQLOrderBy子类类型
     */
    @Override
    public Class<SQLAssignItem> getType() {
        return SQLAssignItem.class;
    }

    /**
     * 解析 SQLPartitions
     *
     * @param partition    partition语句
     * @param tableLineage 当前语句的血缘关系数据
     */
    @Override
    public void analyse(SQLAssignItem partition, TableLineageDto tableLineage) {
        List<String> partitions = tableLineage.getPartitions();
        if (partitions == null) {
            partitions = Lists.newArrayList();
            tableLineage.setPartitions(partitions);
        }
        SQLExpr target = partition.getTarget();
        if (target instanceof SQLIdentifierExpr) {
            partitions.add(((SQLIdentifierExpr) target).getName());
        } else {
            throw new LineageAnalyseException("未实现partition分类类型：" + target.getClass().getName());
        }
    }
}
